﻿using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using NthDownload.Contracts.Plugins.BandwidthProviders;
using System.ComponentModel.Composition;

namespace NthDownload.BandwidthProviderPlugins
{
    [PartCreationPolicy(CreationPolicy.Shared)]
    [Export(typeof(IBandwidthProviderPlugin))]
    public class SpeedLimitBandwidthProviderPlugin : IBandwidthProviderPlugin
    {
        #region Properties

        public string GUID
        {
            get { return "1234"; }
        }

        public string Name
        {
            get { return "Speed Limiter"; }
        }

        public string Description
        {
            get { return "Limits the speed at which downloads are processed"; }
        }

        public string DisplayName
        {
            get
            {
                return "Speed Limiter";
            }
        }

        /// <summary>
        /// The Synchronization Context of the executing thread
        /// </summary>
        [Import(typeof(SynchronizationContext), AllowRecomposition = true)]
        public SynchronizationContext UISynchronizationContext { get; set; }

        #endregion Properties

        #region Methods

        public IBandwidthProviderFactory CreateBandwidthProviderFactory()
        {
            return new SpeedLimitBandwidthProviderFactory(GUID);
        }

        public IBandwidthProviderUIService CreateBandwidthProviderUIService(IBandwidthProviderFactory factory)
        {
            return new SpeedLimitBandwidthProviderUIService(factory);
        }

        public IBandwidthProviderXmlSerializationService CreateXmlSerializationService()
        {
            return new SpeedLimitBandwidthProviderXmlSerializationService(GUID, UISynchronizationContext);
        }

        public Task Initialize()
        {
            Task t = new Task(() =>
            {
                //
                // Load dependencies
                //
                DirectoryInfo di = new DirectoryInfo(GetType().Assembly.Location + ".Dependencies");
                if (!di.Exists) return;

                foreach (FileInfo fi in di.GetFiles())
                {
                    Assembly.LoadFrom(fi.FullName);
                } 
            });

            t.Start();

            return t;
        }

        #endregion Methods
    }
}
